use std::sync::Arc;
use std::thread;
use std::time::Duration;
use std::os::windows::process::CommandExt;
use crate::scum_control::ScumControl;
use crate::frp_setup::FrpSetup;
use std::sync::Mutex;

pub struct StatusMonitor {
    scum_control: Arc<Mutex<ScumControl>>,
    window: Option<tauri::Window>,
    running: Arc<Mutex<bool>>,
}

impl StatusMonitor {
    pub fn new(scum_control: Arc<Mutex<ScumControl>>) -> Self {
        Self {
            scum_control,
            window: None,
            running: Arc::new(Mutex::new(false)),
        }
    }

    pub fn set_window(&mut self, window: tauri::Window) {
        self.window = Some(window);
    }

    pub fn start(&mut self) {
        let running = Arc::clone(&self.running);
        let scum_control = Arc::clone(&self.scum_control);
        let window = self.window.clone();

        {
            let mut running_guard = running.lock().unwrap();
            if *running_guard {
                return; // 已经在运行
            }
            *running_guard = true;
        }

        // 原有状态监控线程
        thread::spawn(move || {
            let mut last_scum_status = false;
            let mut last_frp_status = false;

            loop {
                // 检查是否应该停止
                {
                    let running_guard = running.lock().unwrap();
                    if !*running_guard {
                        break;
                    }
                }

                // 检查SCUM服务器状态
                {
                    let control = scum_control.lock().unwrap();
                    let current_scum_status = control.is_running();
                    
                    if current_scum_status != last_scum_status {
                        last_scum_status = current_scum_status;
                        if let Some(window) = &window {
                            let status = if current_scum_status { "running" } else { "stopped" };
                            let _ = window.emit("scum_status_changed", status);
                        }
                    }
                }

                // 检查FRP状态
                let current_frp_status = FrpSetup::is_frp_running();
                if current_frp_status != last_frp_status {
                    last_frp_status = current_frp_status;
                    if let Some(window) = &window {
                        let status = if current_frp_status { "running" } else { "stopped" };
                        let _ = window.emit("frp_status_changed", status);
                    }
                }

                // 每秒检查一次
                thread::sleep(Duration::from_secs(1));
            }
        });

        // 新增：自动重启检测线程
        let scum_control = Arc::clone(&self.scum_control);
        thread::spawn(move || {
            use chrono::Local;
            use crate::config::AppConfig;
            use std::process::Command;
            let mut last_trigger_minute = String::new();
            
            loop {
                let now = Local::now();
                let current_time = now.format("%H:%M").to_string();

                // 只在分钟变化时检测
                if current_time != last_trigger_minute {
                    last_trigger_minute = current_time.clone();

                    // 读取配置
                    if let Ok(config) = AppConfig::load() {
                        
                        for task in &config.auto_restart_tasks {
                            
                            if task.enabled && task.time == current_time {
                                
                                // 直接检查进程是否在运行（通过配置中的PID）
                                let mut is_running = false;
                                let mut pid_opt = None;
                                if let Some(pid_str) = config.settings.get("scum_process_pid") {
                                    if let Ok(pid) = pid_str.parse::<u32>() {
                                        pid_opt = Some(pid);
                                        // 使用tasklist命令检查进程是否在运行
                                        let output = Command::new("tasklist")
                                            .args(&["/FI", &format!("PID eq {}", pid), "/FO", "CSV"])
                                            .creation_flags(0x08000000) // CREATE_NO_WINDOW
                                            .output();
                                        match output {
                                            Ok(output) => {
                                                let output_str = String::from_utf8_lossy(&output.stdout);
                                                is_running = output_str.contains(&pid.to_string());
                                                println!("[自动重启] 进程PID {} 运行状态: {}", pid, is_running);
                                            }
                                            Err(_) => {
                                                println!("[自动重启] 检查进程状态失败");
                                                is_running = false;
                                            }
                                        }
                                    }
                                }
                                
                                if is_running {
                                    println!("[自动重启] 到点执行定时重启任务: {}", current_time);
                                    let mut control = scum_control.lock().unwrap();
                                    let _ = control.stop_server();
                                    // 等待进程完全退出，最多30秒
                                    if let Some(pid) = pid_opt {
                                        let mut waited = 0;
                                        let max_wait = 180;
                                        loop {
                                            // 重新检测进程是否还在
                                            let output = Command::new("tasklist")
                                                .args(&["/FI", &format!("PID eq {}", pid), "/FO", "CSV"])
                                                .creation_flags(0x08000000) // CREATE_NO_WINDOW
                                                .output();
                                            let still_running = match output {
                                                Ok(output) => {
                                                    let output_str = String::from_utf8_lossy(&output.stdout);
                                                    output_str.contains(&pid.to_string())
                                                }
                                                Err(_) => false
                                            };
                                            if !still_running {
                                                break;
                                            }
                                            thread::sleep(Duration::from_secs(1));
                                            waited += 1;
                                            if waited >= max_wait {
                                                println!("[自动重启] 等待进程退出超时，强制终止进程 PID: {}", pid);
                                                // 强制终止进程
                                                let _ = Command::new("taskkill")
                                                    .args(&["/PID", &pid.to_string(), "/F"])
                                                    .creation_flags(0x08000000) // CREATE_NO_WINDOW
                                                    .output();
                                                // 再等待几秒确保进程被终止
                                                thread::sleep(Duration::from_secs(3));
                                                break;
                                            }
                                        }
                                    }
                                    let exe_path = config.get_scum_server_exe_path().to_string();
                                    let _ = control.start_server(&exe_path);
                                    println!("[自动重启] SCUM服务器已重启");
                                } else {
                                    println!("[自动重启] SCUM服务器未在运行，直接启动");
                                    let mut control = scum_control.lock().unwrap();
                                    let exe_path = config.get_scum_server_exe_path().to_string();
                                    let _ = control.start_server(&exe_path);
                                    println!("[自动重启] SCUM服务器已启动");
                                }
                            }
                        }
                    } else {
                        println!("[自动重启] 读取配置失败");
                    }
                }
                thread::sleep(Duration::from_secs(10)); // 每10秒检测一次
            }
        });
    }

    pub fn stop(&self) {
        let mut running_guard = self.running.lock().unwrap();
        *running_guard = false;
    }
} 